<?php

class MainRouter extends CBaseUrlRule {

    public $connectionID = 'db';
    public $articles = array('article', 'news', 'action', 'static', 'contacts', 'special-offer', 'reviews', 'payment-and-warranty', 'shipping', 'about', 'vacancy', 'cooperation');

    public function createUrl($manager, $route, $params, $ampersand) {
        $arrayUrl = explode('/', $route);
        if (isset($arrayUrl[2]) && $arrayUrl[2] == 'captcha')
            return '/ajax/captcha' . (!empty($params) ? '?' : '') . http_build_query($params, '', '&');
        if (isset($arrayUrl[1]) && $arrayUrl[1] == 'ajax')
            return $route . (!empty($params) ? '?' : '') . http_build_query($params, '', '&');
        return Yii::app()->request->pathInfo . (!empty($params) ? '?' : '') . http_build_query($params, '', '&');
    }

    public function parseUrl($manager, $request, $pathInfo, $rawPathInfo) {
        if (empty($pathInfo))
            return '/main/index';
        $splittedUrl = explode('/', $pathInfo);
        if (count($splittedUrl) == 2 && $splittedUrl[0] == 'product') {
            $product = $this->getProduct(strtolower($pathInfo));
            if (empty($product))
                return '/main/error';
            Controller::$pageData = $product;
            return '/main/product';
        }
        if (count($splittedUrl) >= 1 && in_array(strtolower($splittedUrl[0]), $this->articles)) {
            $article = $this->getArticle(strtolower($pathInfo));
            if (isset($splittedUrl[1])) {
                if (empty($article))
                    return '/main/error';
            }
            if (!empty($article)) {
                $type = strtolower($splittedUrl[0]);
                Controller::$pageType = $type;
                Controller::$pageData = $article;
                return '/article/' . $article['page_template'];
            }
            if (isset($splittedUrl[0]) && !isset($splittedUrl[1])) {
                $type = strtolower($splittedUrl[0]);
                Controller::$pageType = $type;
                return '/article/index';
            }
        }

        $pages = $this->getPage(strtolower($pathInfo));
        if (empty($pages))
            return '/main/error';
        else {
            if ($pages[0]['r_ch_type'] != 'category')
                return '/main/error';
            foreach ($pages as $key => $page) {
                $url[] = $page['r_ch_url'];
                if ($page['r_ch_type'] == 'model')
                    $model = true;
                if ($page['r_ch_type'] == 'brand') {
                    $brand = true;
                }
                if ($page['r_ch_type'] == 'sp_type') {
                    $sp_type = true;
                }
                if ($page['r_ch_type'] == 'category') {
                    $catID = $page['r_ch_id'];
                }
                $ids[$page['r_ch_type']] = $page['r_ch_childs'];
            }
            $url = implode('/', $url);
            if ($url != str_replace('/tags', '', $pathInfo))
                return '/main/error';
            if (isset($model) && !isset($brand))
                return '/main/error';
            if (isset($model))
                unset($ids['brand']);
            $ids = str_replace(',,', ',', implode(',', $ids));
            $products = $this->getProducts($ids);            
            if (empty($products))
                return '/main/error';

            if (isset($sp_type) && !isset($brand)) {
                
                Controller::$filter = array('brands' => $this->getFilter($ids, 'brand'));
            }
            if (!isset($sp_type) && isset($brand)) {
                Controller::$filter = array('types' => $this->getFilter($ids, 'sp_type'));
            }
            if (!isset($sp_type) && !isset($brand)) {
                Controller::$filter = array('brands' => $this->getFilter($ids, 'brand'), 'types' => $this->getFilter($ids, 'sp_type'));
            }
            Controller::$pageData = $products;
            Controller::$pageInfo = $pages;
            return '/main/products';
        }
    }

    private function getFilter($ids, $type = 'sp_type') {
        $sql = 'SELECT * FROM mp_characs WHERE ch_type = \'' . $type . '\' AND ch_id IN(SELECT ch_id FROM mp_prod2ch WHERE prod_id IN(' . $ids . '))';
        return Yii::app()->db->createCommand($sql)->queryAll();
    }

    private function getArticle($url) {
        $sql = 'SELECT page_id, page_title, page_date, page_image, page_short_content, page_full_content, page_template, page_type, page_url FROM {{articles}} WHERE lower(page_url) = :url';
        return Yii::app()->db->createCommand($sql)->bindParam(':url', $url, PDO::PARAM_STR)->queryRow();
    }

    private function getArticles($type) {
        $sql = 'SELECT page_id, page_title, page_date, page_image, page_short_content, page_full_content, page_template FROM {{articles}} WHERE lower(page_type) = :type';
        return Yii::app()->db->createCommand($sql)->bindParam(':type', $type, PDO::PARAM_STR)->queryAll();
    }

    private function getPage($url) {
        $sql = 'select * from check_url(:url)';
        return Yii::app()->db->createCommand($sql)->bindParam(':url', $url, PDO::PARAM_STR)->queryAll();
    }

    private function getProduct($url) {
        $region = $this->getRegion();
        $sql = 'SELECT pr.*, p.prod_title, p.prod_url, p.prod_count, p.prod_image, p.prod_id, p.prod_mspares_artikul FROM mp_products p
                    LEFT JOIN mp__pr_prices pr ON pr.prod_id = p.prod_id AND pr.region_id=' . $region['id'] . '
                    WHERE lower(p.prod_url) = :url';
        return Yii::app()->db->createCommand($sql)->bindParam(':url', $url, PDO::PARAM_STR)->queryRow();
    }

    private function getProducts($ids) {
        $region = $this->getRegion();
        $sql = 'SELECT
                        pr.*, p.prod_title, p.prod_url, p.prod_count, p.prod_image, p.prod_id
                       FROM
                        mp_products P
                       LEFT JOIN mp__pr_prices pr ON pr.prod_id = P .prod_id AND pr.region_id = ' . $region['id'] . '
                       WHERE p.prod_id IN (SELECT prod_id FROM mp_prod2ch WHERE ch_id IN (' . $ids . ')) ORDER BY p.prod_sort';
        return Yii::app()->db->createCommand($sql)->queryAll();
    }

    public function getRegion() {
        $regions = Yii::app()->params['regions'];
        return !empty(Yii::app()->session['region']) ? Yii::app()->session['region'] : $regions[1];
    }

}
